﻿// <copyright file="BestKingsProvider.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Contains the BestKingsProvider provider</summary>

namespace Sqwarea.Persistence.Azure
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Lokad.Cloud.Storage;

    /// <summary>
    /// Provider for best kings
    /// </summary>
    public class BestKingsProvider : IBestKingsProvider
    {
        /// <summary>
        /// Name of the table Storing the logs
        /// </summary>
        public const string BestKingsTableName = "sqwareabestkingstable";

        /// <summary>
        /// table provider
        /// </summary>
        private readonly ITableStorageProvider _tableProvider;
        
        /// <summary>
        /// Initializes a new instance of the BestKingsProvider class.
        /// </summary>
        /// <param name="tableProvider"> a table provider</param>
        [CLSCompliantAttribute(false)]
        public BestKingsProvider(ITableStorageProvider tableProvider)
        {
            if (null == tableProvider)
            {
                throw new ArgumentNullException("tableProvider", "tableProvider must not be null");
            }

            _tableProvider = tableProvider;
            _tableProvider.CreateTable(BestKingsTableName);
        }

        /// <summary>
        /// Returns an array of best kings' ids 
        /// </summary>
        /// <returns>An array of best kings' ids</returns>
        public IEnumerable<King> GetBestKings()
        {
            var bestkings = _tableProvider.Get<King>(BestKingsTableName);
            return from king in bestkings
                   orderby int.Parse(king.RowKey, Tools.NumberFormat) ascending
                   select king.Value;
        }

        /// <summary>
        /// Updates the array of best kings' ids
        /// </summary>
        /// <param name="kinglist">Best kings' ids, sorted by the number of squares the king owns</param>
        public void UpdateBestKings(IEnumerable<King> kinglist)
        {
            var cloudEntities = kinglist.Select(
                                                (king, position) =>
                                                new CloudEntity<King>
                                                {
                                                    Value = king,
                                                    PartitionKey = (position / 500).ToString(Tools.NumberFormat),
                                                    RowKey = position.ToString(Tools.NumberFormat)
                                                });
            _tableProvider.Upsert(BestKingsTableName, cloudEntities);
        }
    }
}
